#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查会话状态接口
"""

from flask import Blueprint, request, jsonify, current_app
from utils.logger import get_logger

kf_service_state_get_bp = Blueprint('kf_service_state_get', __name__)
logger = get_logger(__name__)


@kf_service_state_get_bp.route('/cgi-bin/kf/service_state/get', methods=['POST'])
def get_service_state():
    """检查指定客户的会话状态"""
    try:
        # 获取请求参数
        access_token = request.args.get('access_token')
        
        logger.info("检查会话状态请求")
        
        # 参数验证
        if not access_token:
            logger.warning("缺少access_token参数")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing access_token parameter"
            }), 400
        
        # 获取请求体
        request_data = request.get_json()
        if not request_data:
            logger.warning("缺少请求体")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing request body"
            }), 400
        
        external_userid = request_data.get('external_userid')
        open_kfid = request_data.get('open_kfid')
        
        logger.info(f"检查会话状态 - 用户: {external_userid}, 客服账号: {open_kfid}")
        
        # 参数验证
        if not external_userid or not open_kfid:
            logger.warning("缺少必要参数")
            return jsonify({
                "errcode": 41001,
                "errmsg": "missing required parameters"
            }), 400
        
        # 获取数据管理器
        data_manager = current_app.data_manager
        
        # 验证访问令牌
        if not data_manager.validate_token(access_token):
            logger.warning("无效的access_token")
            return jsonify({
                "errcode": 40014,
                "errmsg": "invalid access_token"
            }), 400
        
        # 获取会话状态
        session = data_manager.get_session(external_userid, open_kfid)
        
        if not session:
            logger.info(f"会话不存在 - 用户: {external_userid}, 客服账号: {open_kfid}")
            return jsonify({
                "errcode": 0,
                "errmsg": "ok",
                "service_state": 4,  # 已结束/未开始
                "servicer_userid": ""
            })
        
        # 更新统计信息
        data_manager.update_stats(success=True)
        
        logger.info(f"获取会话状态成功 - 状态: {session.get('service_state')}")
        
        return jsonify({
            "errcode": 0,
            "errmsg": "ok",
            "service_state": session.get('service_state', 4),
            "servicer_userid": session.get('servicer_userid', '')
        })
        
    except Exception as e:
        logger.error(f"检查会话状态失败: {e}")
        data_manager = current_app.data_manager
        data_manager.update_stats(success=False)
        
        return jsonify({
            "errcode": 500,
            "errmsg": "internal error"
        }), 500
